package Server

import (
	"encoding/json"
	"errors"
	"io/ioutil"
	"log"
)

type BearerConfigItem struct {
	Headers    map[string]string `json:"headers"`
	Interfaces []string          `json:"interfaces"`
}

type BearerConfigAuth struct {
	Configs map[string]*BearerConfigItem // token =》 config item
}

func (this *BearerConfigAuth) GetAuthInfo(token string, url string) (err error, headers map[string]string) {
	configItem := this.Configs[token]
	if configItem == nil {
		err = errors.New("not found token")
		return
	}

	if IndexOf(configItem.Interfaces, url) == -1 {
		err = errors.New("un-authorized")
		return
	}

	headers = make(map[string]string)
	for k, v := range configItem.Headers {
		headers[k] = v
	}

	return
}

func (this *BearerConfigAuth) InitWithConfig(config map[string]string) {
	cFile := config["file"]
	if cFile == "" {
		return
	}

	data, err := ioutil.ReadFile(cFile)
	if err != nil {
		log.Panic(err)
	}

	var m map[string]*BearerConfigItem

	//this.Configs = make(map[string]*BearerConfigItem)
	err = json.Unmarshal(data, &m)
	if err != nil {
		log.Panic(err)
	}

	this.Configs = m
}

func IndexOf(array []string, item string) int {
	for i := 0; i < len(array); i++ {
		if array[i] == item {
			return i
		}
	}

	return -1
}
